package com.jhy.system.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jhy.core.domain.LoginUser;
import com.jhy.core.enums.DeviceType;
import com.jhy.core.helper.LoginHelper;
import com.jhy.core.utils.Check;
import com.jhy.exception.BaseException;
import com.jhy.system.domain.SysUser;
import com.jhy.system.domain.SysUserFriend;
import com.jhy.system.domain.bo.AddFriendBo;
import com.jhy.system.domain.bo.EditFriendApplyBo;
import com.jhy.system.domain.bo.SysUserLoginBo;
import com.jhy.system.domain.vo.SysUserFriendVo;
import com.jhy.system.mapper.SysUserFriendMapper;
import com.jhy.system.mapper.SysUserMapper;
import com.jhy.system.service.ISysUserFriendService;
import com.jhy.system.service.ISysUserService;
import com.jhy.ws.storage.WebSocketSessionStorage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeoutException;

@Slf4j
@Service
@RequiredArgsConstructor
public class SysUserFriendServiceImpl implements ISysUserFriendService {

    private final SysUserFriendMapper friendMapper;
    private final SysUserMapper userMapper;


    @Override
    public Boolean add(AddFriendBo bo) throws TimeoutException {
        // 判断是否重复添加好友
        LambdaQueryWrapper<SysUserFriend> wrapper = new LambdaQueryWrapper<>();
        List<Long> userIds = Arrays.asList(LoginHelper.getUserId(), bo.getFriendUserId());
        wrapper.in(SysUserFriend::getUserId, userIds);
        wrapper.in(SysUserFriend::getFriendUserId, userIds);
        wrapper.last("limit 1");
        SysUserFriend sysUserFriend = friendMapper.selectOne(wrapper);
        if(Check.isNoEmpty(sysUserFriend)){
            switch (sysUserFriend.getFriendStatus()){
                case 0:
                    throw new BaseException("已提交申请，等待对方同意");
                case 1:
                case 2:
                case 3:
                    throw new BaseException("该好友已添加");
            }
            throw new BaseException("该好友已添加");
        }
        sysUserFriend = new SysUserFriend();
        sysUserFriend.setUserId(LoginHelper.getUserId());
        sysUserFriend.setUserName(LoginHelper.getUsername());
        sysUserFriend.setFriendUserId(bo.getFriendUserId());
        sysUserFriend.setFriendUserName(bo.getFriendUserName());
        sysUserFriend.setAddRemark(bo.getAddRemark());
        friendMapper.insert(sysUserFriend);
        return true;
    }

    @Override
    public List<SysUserFriendVo> applyList() {
        LambdaQueryWrapper<SysUserFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserFriend::getFriendUserId, LoginHelper.getUserId());
        List<SysUserFriendVo> sysUserFriendVos = friendMapper.selectVoList(wrapper, SysUserFriendVo.class);
        if (Check.isNoEmpty(sysUserFriendVos)){
            for (SysUserFriendVo item : sysUserFriendVos) {
                switch (item.getFriendStatus()){
                    case 0:
                        item.setFriendStatusText("点击审核");
                        break;
                    case 1:
                        item.setFriendStatusText("已通过");
                        break;
                    case 2:
                        item.setFriendStatusText("已拒绝");
                        break;
                    case 3:
                        item.setFriendStatusText("已删除");
                        break;
                }
            }
        }
        return sysUserFriendVos;
    }

    @Override
    public List<SysUserFriendVo> friendList() {
        LambdaQueryWrapper<SysUserFriend> wrapper =  buildWrapper();
        wrapper.eq(SysUserFriend::getFriendStatus, 1);
        List<SysUserFriendVo> sysUserFriendVos = friendMapper.selectVoList(wrapper, SysUserFriendVo.class);
        if (Check.isNoEmpty(sysUserFriendVos)){
            // 查询是否在线
            for (SysUserFriendVo item : sysUserFriendVos) {
                WebSocketSessionStorage.SESSION_MAP.keySet().forEach(k -> {
                    String userId = LoginHelper.getUserId().toString();
                    if (
                            (!item.getFriendUserId().toString().equals(userId))
                            && k.contains(item.getFriendUserId().toString())
                                    || (!item.getUserId().toString().equals(userId))
                                            && k.contains(item.getUserId().toString())
                    ){
                        item.setOnlineStatus(1);
                        item.setOnlineStatusText("在线");
                    }
                });
            }
        }
        return sysUserFriendVos;
    }

    @Override
    public Boolean editFriendApply(EditFriendApplyBo bo) {
        friendMapper.updateById(BeanUtil.toBean(bo,SysUserFriend.class));
        return true;
    }

    @Override
    public SysUserFriendVo findByUserName(String userName) {
        SysUserFriendVo sysUserFriendVo = new SysUserFriendVo();
        if (Check.isEmpty(userName)){
            return sysUserFriendVo;
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUserName, userName);
        SysUser sysUser = userMapper.selectOne(wrapper);
        if (Check.isNoEmpty(sysUser)){
            sysUserFriendVo.setFriendUserId(sysUser.getUserId());
            sysUserFriendVo.setFriendUserName(sysUser.getUserName());
            // 查询好友状态
            LambdaQueryWrapper<SysUserFriend> friendWrapper = new LambdaQueryWrapper<>();
            friendWrapper.and(w->{
                w.eq(SysUserFriend::getUserId, LoginHelper.getUserId())
                        .or()
                        .eq(SysUserFriend::getUserId, sysUser.getUserId());
            });
            friendWrapper.and(w->{
                w.eq(SysUserFriend::getFriendUserId, LoginHelper.getUserId())
                        .or()
                        .eq(SysUserFriend::getFriendUserId, sysUser.getUserId());
            });
            SysUserFriend userFriend = friendMapper.selectOne(friendWrapper);
            if (Check.isNoEmpty(userFriend)){
                sysUserFriendVo.setFriendStatus(userFriend.getFriendStatus());
                switch (userFriend.getFriendStatus()){
                    case 0:
                        sysUserFriendVo.setFriendStatusText("待通过");
                        break;
                    case 1:
                    case 3:
                        sysUserFriendVo.setFriendStatusText("已通过");
                        break;
                    case 2:
                        sysUserFriendVo.setFriendStatusText("已拒绝");
                        break;
                }
            }

        }
        return sysUserFriendVo;
    }

    @Override
    public List<SysUserFriendVo> findFriendByUserName(String userName) {
        LambdaQueryWrapper<SysUserFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w->{
            w.eq(SysUserFriend::getFriendUserName, userName)
                    .or()
                    .eq(SysUserFriend::getUserName, userName);
        });
        wrapper.orderByDesc(SysUserFriend::getId);
        wrapper.eq(SysUserFriend::getFriendStatus, 1);
        return friendMapper.selectVoList(wrapper,SysUserFriendVo.class);
    }

    private LambdaQueryWrapper<SysUserFriend> buildWrapper() {
        LambdaQueryWrapper<SysUserFriend> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(w->{
            w.eq(SysUserFriend::getFriendUserId, LoginHelper.getUserId())
                    .or()
                    .eq(SysUserFriend::getUserId, LoginHelper.getUserId());
        });
        wrapper.orderByDesc(SysUserFriend::getId);
        return wrapper;
    }
}
